<?php

class Menu {

    private static $_controller;

    public static function getMenu($controller) {
        self::$_controller = $controller;
        $items = array(
            array('label' => '<i class="icon-dashboard"></i> Menu', 'url' => Yii::app()->homeUrl, 'access' => 'action_dashboard_index', 'active_rules' => array('module' => 'clientes', 'controller' => 'dashboard')),
//            array('label' => '<i class="icon-briefcase"></i> Otras Personas', 'url' => array('/clientes/empresa/admin'), 'access' => 'action_empresa_admin', 'active_rules' => array('module' => 'clientes', 'controller' => 'empresa')),
            array('label' => '<i class="icon-book"></i>  Registrar', 'url' => array('/clientes/persona/admin'), 'items' => array(
                    array('label' => '<i class="icon-group"></i> Personas', 'url' => array('/clientes/persona/admin'), 'access' => 'action_persona_admin', 'active_rules' => array('module' => 'clientes', 'controller' => 'persona')),
                    array('label' => '<i class="icon-folder-open"></i>Sanciones', 'url' => array('/clientes/sanciones/admin'), 'access' => 'action_sanciones_admin', 'active_rules' => array('module' => 'clientes', 'controller' => 'sanciones')),
//                    array('label' => '<i class="icon-briefcase"></i>Novedades', 'url' => array('/clientes/persona/admin'), 'access' => 'action_persona_admin', 'active_rules' => array('module' => 'clientes', 'controller' => 'persona')),
                )),
            array('label' => '<i class="icon-fire-extinguisher"></i>  Catalogos', 'url' => '#', 'items' => array(
                    array('label' => 'Grados', 'url' => array('/clientes/grado/'), 'access' => 'action_grado_admin', 'active_rules' => array('module' => 'clientes', 'controller' => 'grado')),
                    array('label' => 'Parentesco', 'url' => array('/clientes/Parentesco/'), 'access' => 'action_parentesco_admin', 'active_rules' => array('module' => 'clientes', 'controller' => 'parentesco')),
                    array('label' => 'Generos', 'url' => array('/clientes/genero/'), 'access' => 'action_genero_admin', 'active_rules' => array('module' => 'clientes', 'controller' => 'genero')),
                    array('label' => 'Provincia', 'url' => array('/clientes/provincia/'), 'access' => 'action_provincia_admin', 'active_rules' => array('module' => 'clientes', 'controller' => 'provincia')),
                    array('label' => 'Tipo Sangre', 'url' => array('/clientes/tipoSangre/'), 'access' => 'action_tipoSangre_admin', 'active_rules' => array('module' => 'clientes', 'controller' => 'tipoSangre')),
//                    array('label' => 'Tipo Telefono', 'url' => array('/clientes/tipoTelefono/'), 'access' => 'action_tipoTelefono_admin', 'active_rules' => array('module' => 'clientes', 'controller' => 'tipoTipoTelefono')),
                    array('label' => 'Tipo Operadora', 'url' => array('/clientes/tipoOperadora/'), 'access' => 'action_tipoOperadora_admin', 'active_rules' => array('module' => 'clientes', 'controller' => 'tipoTipoOperadora')),
                    array('label' => 'Licencia', 'url' => array('/clientes/licencia/'), 'access' => 'action_licencia_admin', 'active_rules' => array('module' => 'clientes', 'controller' => 'licencia')),
                    array('label' => 'Vuelo', 'url' => array('/clientes/vuelo/'), 'access' => 'action_vuelo_admin', 'active_rules' => array('module' => 'clientes', 'controller' => 'vuelo')),
                )),
        );

        return self::generateMenu($items);
    }

    public static function getAdminMenu($controller) {
        self::$_controller = $controller;
        $items = array(
            array('label' => '<i class="icon-mail-reply"></i>  Regresar', 'url' => Yii::app()->homeUrl),
            array('label' => '<i class="icon-book"></i>  Configuración', 'url' => '#', 'items' => array(
                    array('label' => 'Config', 'url' => array('/llamadas/configuracion/admin'), 'access' => 'action_configuracion_admin', 'active_rules' => array('module' => 'llamadas', 'controller' => 'configuracion')),
                    array('label' => 'Otra opcion', 'url' => array('#'), 'access' => 'action_tareaEtapa_admin', 'active_rules' => array('module' => 'tareas', 'controller' => 'tareaEtapa')),
                )),
            array('label' => '<i class="icon-user"></i>  Usuarios', 'url' => Yii::app()->user->ui->userManagementAdminUrl, 'access' => 'Cruge.ui.*', 'active_rules' => array('module' => 'cruge')),
//            array('label' => '<i class="icon-archive"></i> Grupos', 'url' => array('/crm/grupo/admin'), 'access' => 'action_grupo_admin', 'active_rules' => array('module' => 'crm', 'controller' => 'grupo')),
//            array('label' => '<i class="icon-book"></i>  Catálogos', 'url' => '#', 'items' => array(
//                    array('label' => 'Industrias', 'url' => array('/crm/industria/admin'), 'access' => 'action_industria_admin', 'active_rules' => array('module' => 'crm', 'controller' => 'industria')),
//                    array('label' => 'Etapas de Oportunidad', 'url' => array('/oportunidades/oportunidadEtapa/admin'), 'access' => 'action_oportunidadEtapa_admin', 'active_rules' => array('module' => 'oportunidades', 'controller' => 'oportunidadEtapa')),
//                    array('label' => 'Etapas de Tarea', 'url' => array('/tareas/tareaEtapa/admin'), 'access' => 'action_tareaEtapa_admin', 'active_rules' => array('module' => 'tareas', 'controller' => 'tareaEtapa')),
//                )),
//            array('label' => '<i class="icon-comments"></i>  Sms', 'url' => '#', 'items' => array(
//                    array('label' => 'Motivos', 'url' => array('/sms/smsMotivo/admin'), 'access' => 'action_smsMotivo_admin', 'active_rules' => array('module' => 'sms', 'controller' => 'smsMotivo')),
//                    array('label' => 'Plantillas', 'url' => array('/sms/smsPlantilla/admin'), 'access' => 'action_smsPlantilla_admin', 'active_rules' => array('module' => 'sms', 'controller' => 'smsPlantilla')),
//                )),
//            array('label' => '<i class="icon-envelope"></i>  Mail', 'url' => '#', 'items' => array(
//                    array('label' => 'Asunto', 'url' => array('/mail/mailAsunto/admin'), 'access' => 'action_mailAsunto_admin', 'active_rules' => array('module' => 'mail', 'controller' => 'mailAsunto')),
//                    array('label' => 'Plantillas', 'url' => array('/mail/mailPlantilla/admin'), 'access' => 'action_mailPlantilla_admin', 'active_rules' => array('module' => 'mail', 'controller' => 'mailPlantilla')),
//                )),
            array('label' => '<i class="icon-fire-extinguisher"></i>  Catalogos', 'url' => '#', 'items' => array(
                    array('label' => 'Grados', 'url' => array('/grado/grado/'), 'access' => 'action_grado_admin', 'active_rules' => array('module' => 'grado', 'controller' => 'grado')),
//                    array('label' => 'Categorías  - Motivos', 'url' => array('/incidencias/incidenciaCategoria/incidenciaCategoria'), 'access' => 'action_incidenciaCategoria_incidenciaCategoria', 'active_rules' => array('module' => 'incidencias', 'controller' => 'incidenciaCategoria')),
//                    array('label' => 'Áreas', 'url' => array('/incidencias/incidenciaArea/createAreaUsuarioArea'), 'access' => 'action_incidenciaArea_createAreaUsuarioArea', 'active_rules' => array('module' => 'incidencias', 'controller' => 'incidenciaArea')),
//                    array('label' => 'Tipos', 'url' => array('/incidencias/incidenciaTipo'), 'access' => 'action_incidenciaTipo_admin', 'active_rules' => array('module' => 'incidencias', 'controller' => 'incidenciaTipo')),
//                    array('label' => 'Estados', 'url' => array('/incidencias/incidenciaEstado/admin'), 'access' => 'action_incidenciaEstado_admin', 'active_rules' => array('module' => 'incidencias', 'controller' => 'incidenciaEstado')),
//                    array('label' => 'Sub Motivos', 'url' => array('/incidencias/incidenciaSubmotivo/admin'), 'access' => 'action_incidenciaSubmotivo_admin', 'active_rules' => array('module' => 'incidencias', 'controller' => 'incidenciaSubmotivo')),
//                    array('label' => 'Vías de ingreso', 'url' => array('/incidencias/incidenciaViaIngreso/admin'), 'access' => 'action_incidenciaViaIngreso_admin', 'active_rules' => array('module' => 'incidencias', 'controller' => 'incidenciaViaIngreso')),
//                    array('label' => 'Prioridades', 'url' => array('/incidencias/incidenciaPrioridad/admin'), 'access' => 'action_incidenciaPrioridad_admin', 'active_rules' => array('module' => 'incidencias', 'controller' => 'incidenciaPrioridad')),
                )),
//            array('label' => '<i class="icon-calendar"></i>  Eventos', 'url' => '#', 'items' => array(
//                    array('label' => 'Prioridad', 'url' => array('/eventos/eventoPrioridad/admin'), 'access' => 'action_eventoPrioridad_admin', 'active_rules' => array('module' => 'eventos', 'controller' => 'eventoPrioridad')),
//                )),
//            array('label' => '<i class="icon-phone"></i>  Llamadas', 'url' => '#', 'items' => array(
//                    array('label' => 'Motivos', 'url' => array('/llamadas/llamadaMotivo/admin'), 'access' => 'action_llamadaMotivo_admin', 'active_rules' => array('module' => 'llamadas', 'controller' => 'llamadaMotivo')),
//                    array('label' => 'Submotivos', 'url' => array('/llamadas/llamadaSubmotivo/admin'), 'access' => 'action_llamadaSubmotivo_admin', 'active_rules' => array('module' => 'llamadas', 'controller' => 'llamadaSubmotivo')),
//                    array('label' => 'Subestados', 'url' => array('/llamadas/llamadaSubestado/admin'), 'access' => 'action_llamadaSubestado_admin', 'active_rules' => array('module' => 'llamadas', 'controller' => 'llamadaSubestado')),
//                )),
//            array('label' => '<i class="icon-time"></i>  Actividades', 'url' => array('/actividades/actividad/admin'), 'access' => 'action_actividad_admin', 'active_rules' => array('module' => 'actividades')),
//            array('label' => '<i class="icon-trophy"></i>  Gamification', 'url' => array('/gamification/gamesLogro/admin'), 'access' => 'action_gamesLogro_admin', 'active_rules' => array('module' => 'gamification')),
//            array('label' => '<i class="icon-file-text"></i>  Encuestas', 'url' => array('/nosey/'), 'access' => '', 'active_rules' => array('module' => 'nosey')),
        );

        return self::generateMenu($items);
    }

    /**
     * Function to create a menu with acces rules and active item
     * @param array $items items to build the menu
     * @return array the formated menu
     */
    private static function generateMenu($items) {
        $menu = array();

        foreach ($items as $k => $item) {
            $access = false;
            $menu_item = $item;

            // Check children access
            if (isset($item['items'])) {
                $menu_item['items'] = array();
                // Check childrens access
                foreach ($item['items'] as $j => $children) {
                    if ($access = Yii::app()->user->checkAccess($children['access'])) {
                        $menu_item['items'][$j] = $children;
                        if (isset($children['active_rules']) && self::getActive2($children['active_rules'])) {
                            $menu_item['items'][$j]['active'] = true;
                            $menu_item['active'] = true;
                        }
                    }
                }
            } else {
                // Check item access
                if (isset($item['access'])) {
                    $access = Yii::app()->user->checkAccess($item['access']);
                } else {
                    $access = true;
                }
                // Check active
                if (isset($item['active_rules'])) {
                    $menu_item['active'] = self::getActive2($item['active_rules']);
                }
            }

            // If acces to the item or any child add to the menu
            if ($access) {
                $menu[] = $menu_item;
            }
        }

        return $menu;
    }

    /*     * manejo de activos en el menu 
     * @author Alex Yepez <ayepez@tradesystem.com.ec>
     */

    private static function getActive2($active_rules) {
        $current = false;
        //MODULE
        $module = false;
        //CONTROLLER
        $controller = FALSE;
        //ACTION
        $action = false;
        if (self::$_controller) {
            if (is_array(current($active_rules))) {
                foreach ($active_rules as $rule) {
                    $operator = isset($rule['operator']) ? $rule['operator'] : '==';
                    if (isset($rule['module'])) {
                        if (self::$_controller->module) {
                            $module = self::BooleanOperator($operator, self::$_controller->module->id, $rule['module']);
                        }
                    } else {
                        $module = true;
                    }
                    if (isset($rule['controller'])) {
                        $controller = self::BooleanOperator($operator, self::$_controller->id, $rule['controller']);
                    } else {
                        $controller = true;
                    }
                    if (isset($rule['action'])) {
                        $action = self::BooleanOperator($operator, self::$_controller->action->id, $rule['action']);
                    } else {
                        $action = true;
                    }
                    if (!isset($rule['controller']) && !isset($rule['module']) && !isset($rule['action']))
                        $current = false;
                    else
                        $current = $module && $controller && $action;
                    if (!$current)
                        break;
                }
            } else {
                $operator = isset($active_rules['operator']) ? $active_rules['operator'] : '==';
                if (isset($active_rules['module'])) {
                    if (self::$_controller->module) {
                        $module = self::BooleanOperator($operator, self::$_controller->module->id, $active_rules['module']);
                    }
                } else {
                    $module = true;
                }
                if (isset($active_rules['controller'])) {
                    $controller = self::BooleanOperator($operator, self::$_controller->id, $active_rules['controller']);
                } else {
                    $controller = true;
                }
                if (isset($active_rules['action'])) {
                    $action = self::BooleanOperator($operator, self::$_controller->action->id, $active_rules['action']);
                } else {
                    $action = true;
                }
                if (!isset($active_rules['controller']) && !isset($active_rules['module']) && !isset($active_rules['action']))
                    $current = false;
                else
                    $current = $module && $controller && $action;
//                var_dump($current);
            }
        }
        return $current;
    }

    private static function BooleanOperator($operator, $compare1, $compare2) {
        $result = FALSE;
        if ($operator == "==")
            $result = $compare1 == $compare2;
        if ($operator == "!=")
            $result = $compare1 != $compare2;

        return $result;
    }

}
